package com.li.utils;


import com.li.DTO.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Component
public class HTMLParseUtil {

    public List<Content> parseJD(String keyWords) throws  Exception{
        String url = "https://search.jd.com/Search?keyword="+keyWords;
        Document document = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12").timeout(30000).get();
        Element element = document.getElementById("J_goodsList");
        Elements li = element.getElementsByTag("li");
        LinkedList<Content> goodsList = new LinkedList<>();
        for (Element el : li) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content().setImg(img).setPrice(price).setTitle(title);
            goodsList.add(content);
        }
        return goodsList;
    }

}
